package com.abu.authms.service;

import com.abu.authms.client.UcenterClient;
import com.abu.authms.utils.JwtUtils;
import com.abu.ucenter.pojo.Member;
import com.abu.utils.Resp;
import com.alibaba.fastjson.JSON;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import springfox.documentation.spring.web.json.Json;

import java.util.HashMap;

@Service
public class AuthService {

    @Autowired
    private UcenterClient ucenterClient;


    public String checkLogin(Object data) {

        String jwtToken = null;
//        转成map对象
        String jsonData = JSON.toJSONString(data);
        HashMap map = JSON.parseObject(jsonData, HashMap.class);
//        获取nickname等信息
        String fromNickname = (String) map.get("nickname");
        String avatar = (String) map.get("avatar");
        String gender = (String) map.get("gender");
        Object token = map.get("token");
        String jsonTokenString = JSON.toJSONString(token);
        HashMap tokenMap = JSON.parseObject(jsonTokenString, HashMap.class);
//        获取用户的唯一标识
        String openId = tokenMap.get("openId").toString();
//        查询用户是否存在
        Member member = this.ucenterClient.queryMemberByOpenId(openId);
//        如果不存在则添加用户
        if (member == null) {
            member = new Member();
            member
                    .setNickname(fromNickname)
                    .setAvatar(!StringUtils.isEmpty(avatar) ? avatar : "https://abu-edu.oss-cn-beijing.aliyuncs.com/2020-06-17/2bda122fe5b54e7ea2741b0ea0b272a5·file.png")
                    .setSex(StringUtils.equals(gender, "男") ? 2 : 1)
                    .setOpenid(openId);
            Member fromMember = this.ucenterClient.save(member);
            jwtToken = JwtUtils.getJwtToken(fromMember.getId(), fromNickname);
            return jwtToken;
        }
//        如果存在则将用户信息生成token信息
        jwtToken = JwtUtils.getJwtToken(member.getId(), fromNickname);
        return jwtToken;
    }
}
